﻿using cooc.Properties;
using Meebey.SmartIrc4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace cooc
{
    public delegate void OnReciveMessage(string user, string msg);

    public class IRCServer
    {
        public event OnReciveMessage ReciveMessageEvt;
        public static Thread listener = new Thread(() => { while (DeamonServer.workstatus) { client.ListenOnce(false); } });
        private static IrcClient client = null;

        private const string CONST_ACTION_FLAG = "\x0001ACTION ";
        private const string USERNAME = "_CooC_";
        private const string PASSWORD = "761ad449";
        private const string SERVER = "irc.ppy.sh";
        private const int PORT = 6667;

        public IRCServer()
        {
            client = new IrcClient()
            {
                AutoReconnect = true,
                AutoRelogin = true,
                AutoRejoinOnKick = false,
            };

        }

        private void Client_OnRawMessage(object sender, IrcEventArgs e)
        {
            if (e.Data.Type == ReceiveType.ChannelAction || e.Data.Type == ReceiveType.QueryAction || e.Data.Type == ReceiveType.QueryMessage || e.Data.Type == ReceiveType.ChannelMessage)
                ReciveMessageEvt?.Invoke(e.Data.Nick, e.Data.Message);
        }

        public void Connect()
        {
            client.EnableUTF8Recode = true;
            try
            {
                client.Connect(SERVER, PORT);
                client.Login(USERNAME, USERNAME, 1, USERNAME, PASSWORD);
                client.OnRawMessage += Client_OnRawMessage;
                listener.Start();
            }
            catch (Exception e)
            {
                throw e;
            }

        }

        public void Disconnect()
        {
            client.Disconnect();
        }

        public void SendMessage(string Message)
        {
            client.WriteLine(Message);
        }

        public bool GetServerStatus()
        {
            return client.IsConnected;
        }
    }
}
